class Solution
{
public:
    int findMaxLength(vector<int> &nums)
    {
        int n = nums.size(), count = 0, ans = 0;
        unordered_map<int, int> m;
        m[count] = -1;
        for (int i = 0; i < n; i++)
        {
            if (nums[i] == 1)
            {
                count++;
            }
            else
            {
                count--;
            }
            if (m.count(count))
            {
                ans = max(ans, i - m[count]);
            }
            else
            {
                m[count] = i;
            }
        }
        return ans;
    }
};